<?php
declare(strict_types=1);
namespace Model;
// hook model_store_product_use.php
use App\Model;
use Field\StoreProductConst;
use Field\StoreProductColumns;
use Field\StoreProductRow;

class StoreProductModel extends Model
{
    // hook model_store_product_public_start.php
    public string $table = 'store_product';

    public array $with = [];

    // hook model_store_product_public_end.php
    /**
     * 插入
     */
    public function insert(StoreProductColumns|array $val):int|null
    {
        // hook model_store_product_insert_start.php
        $new = is_array($val) ? $val : $val->toArray();
        // hook model_store_product_insert_end.php
        return $this->db->insert($this->table, $new);
    }

    /**
     * 批量插入
     */
    public function insertALL(array $data):bool|int
    {
        // hook model_store_product_insertALL_start.php
        foreach ($data as &$new){
            // hook model_store_product_insertALL_walk_start.php
            $new = (new StoreProductRow($new))->toArray();
            // hook model_store_product_insertALL_walk_end.php
        }
        // hook model_store_product_insertALL_end.php
        return $this->db->insert_batch($this->table, $data);
    }

    /**
     * 读取一行到数组
     */
    public function read(array $cond, $select = '*'):array
    {
        // hook model_store_product_read_start.php
        $data = $this->find_one($cond,[], $select);
        // hook model_store_product_read_end.php
        return $data;
    }

    /**
     * 读取一行
     */
    public function readRow(array $cond):StoreProductColumns
    {
        // hook model_store_product_read_start.php
        $one = $this->read($cond);
        $data =  (new StoreProductRow(!empty($one)?$one:[]))->data;
        // hook model_store_product_read_end.php
        return $data;
    }

    

    /**
     * 根据主键取数据
     */
    public function readByPk(int $ProductID):StoreProductColumns
    {
        $cond=[];
        // hook model_store_product_read_by_pk_start.php
        $cond['ProductID']=$ProductID;
        // hook model_store_product_read_by_pk_end.php
        return $this->readRow($cond);
    }

    /**
     * 根据主键取数据
     */
    public function read_by_pk(int $ProductID):array
    {
        $cond=[];
        // hook model_store_product_read_by_pk_start.php
        $cond['ProductID']=$ProductID;
        // hook model_store_product_read_by_pk_end.php
        return $this->read($cond);
    }

    /**
     * 使用主键删除数据
     */
    public function deleteByPk(array|int $pk_arr):bool|int
    {
        // hook model_store_product_delete_by_pk_start.php
        $cond=[StoreProductConst::pk=>$pk_arr];
        if(in_array('IsDelete',StoreProductConst::fields,true)){
            $new =[];
            $new["IsDelete"]=1;
            // hook model_store_product_delete_by_pk_end.php
            return !empty($cond) ? $this->db->update($this->table, $cond, $new):false;
        }else{
            // hook model_store_product_delete_by_pk_end.php
            return !empty($cond) ? $this->db->delete($this->table, $cond):false;
        }
    }

    /**
     * 使用主键更新数据
     */
    public function updateByPk(array|int $pk_arr,array $new):bool|int
    {
        // hook model_store_product_update_by_pk_start.php
        $cond=[StoreProductConst::pk=>$pk_arr];
        // hook model_store_product_update_by_pk_end.php
        return !empty($cond) ? $this->db->update($this->table, $cond, $new):false;
    }
    

    
    /**
     * 根据索引取数据
     */
    public function readByIndex(array $row):StoreProductColumns
    {
        $cond=[];
        // hook model_store_product_read_by_index_start.php
        isset($row['ProductID'])	&& $cond['ProductID']=$row['ProductID'];
        // hook model_store_product_read_by_index_end.php
        return $this->readRow($cond);
    }

    /**
     * 根据索引取数据
     */
    public function read_by_index(int $ProductID):array
    {
        $cond=[];
        // hook model_store_product_read_by_index_start.php
        $cond['ProductID']=$ProductID;
        // hook model_store_product_read_by_index_end.php
        return $this->read($cond);
    }

    /**
     * 使用索引删除数据
     */
    public function deleteByIndex(array $cond_array):bool|int
    {
        // hook model_store_product_delete_by_index_start.php
        $cond_arr=[];
        foreach($cond_array as $row){
	        $cond_arr['ProductID'][]=$row['ProductID'];
       }
        if(in_array('IsDelete',StoreProductConst::fields,true)){
            $new =[];
            $new["IsDelete"]=1;
            // hook model_store_product_delete_by_index_end.php
            return !empty($cond_arr) ? $this->db->update($this->table, $cond_arr, $new):false;
        }else{
            // hook model_store_product_delete_by_index_end.php
            return !empty($cond_arr) ? $this->db->delete($this->table, $cond_arr):false;
        }
    }

    /**
     * 使用索引更新数据
     */
    public function updateByIndex(array $cond_array,array $new):bool|int
    {
        // hook model_store_product_update_by_index_start.php
        $cond_arr=[];
        foreach($cond_array as $row){
	        $cond_arr['ProductID'][]=$row['ProductID'];
       }
        // hook model_store_product_update_by_index_end.php
        return !empty($cond_arr) ? $this->db->update($this->table, $cond_arr, $new):false;
    }
    
    /**
     * 字段统计
     * @param array $cond
     * @param string $select
     * @return int
     */
    public function count(array $cond = [],string $select = '*'):int
    {
        // hook model_store_product_count_start.php
          !isset($cond['IsDelete']) && $cond['IsDelete'] = 0;
        $count = $this->db->count($this->table, $cond, $select);
        // hook model_store_product_count_end.php
        return $count;
    }

    /**
     * 字段求和
     * @param string $column
     * @param array $cond
     * @return int
     */
    public function sum(string $column,array $cond=[]):int
    {
        // hook model_store_product_sum_start.php
          !isset($cond['IsDelete']) && $cond['IsDelete'] = 0;
        $count = $this->db->sum($this->table,$column, $cond);
        // hook model_store_product_sum_end.php
        return $count;
    }

    /**
     * 字段最大数值
     * @param string $column
     * @param array $cond
     * @return int
     */
    public function max(string $column,array $cond=[]):int
    {
        // hook model_store_product_max_start.php
          !isset($cond['IsDelete']) && $cond['IsDelete'] = 0;
        $count = $this->db->Max($this->table,$column, $cond);
        // hook model_store_product_max_end.php
        return $count;
    }

    /**
     * 字段最小数值
     * @param string $column
     * @param array $cond
     * @return int
     */
    public function min(string $column,array $cond=[]):int
    {
        // hook model_store_product_min_start.php
          !isset($cond['IsDelete']) && $cond['IsDelete'] = 0;
        $count = $this->db->Min($this->table,$column, $cond);
        // hook model_store_product_min_end.php
        return $count;
    }

    /**
     * 更新数据
     * @param array $cond
     * @param array $new
     */
    public function update(array $cond,array $new):bool|int
    {
        // hook model_store_product_update_start.php
          !isset($cond['IsDelete']) && $cond['IsDelete'] = 0;
        // hook model_store_product_update_end.php
        return !empty($cond) ? $this->db->update($this->table, $cond, $new):false;
    }

    /**
     * 删除数据
     * @param array $cond
     */
    public function delete(array $cond):bool|int
    {
        // hook model_store_product_delete_start.php
        if(in_array('IsDelete',StoreProductConst::fields,true)){
            $new=[];
            $new["IsDelete"]=1;
            // hook model_store_product_delete_end.php
            return !empty($cond) ? $this->db->update($this->table, $cond, $new):false;
        }else{
            // hook model_store_product_delete_end.php
            return !empty($cond) ? $this->db->delete($this->table, $cond):false;
        }
    }

    /**
     * 关联查询
     * @param array  $table ['user b'=>['JOIN'=>'left','ON'=>'a.uid=b.uid']]
     * @param array $order
     * @param int    $page
     * @param int    $limit
     * @param string $select
     * @param int    $by_page
     * @param string $group
     * @return array|bool
     */
	public function GetListWith(array $join = [], array $cond = [], array $order = [], int $page = 1, int $limit = 1000, string $select = '*', bool $by_page = true, string $group = '')
    {
        $str = [];
        foreach ($join as $k=> $v) {
            $str[] = (empty($v['JOIN']) ? 'LEFT' : $v['JOIN']) . ' JOIN ' . str_replace('.',' a', $k) . ' ON ' . $v['ON'];
        }
        $sql = $this->table . ' a1 ' . implode(' ', $str);
        if (!$by_page) {
            $result['data']  = $this->db->find($sql, $cond, $order, $page, $limit, '', $select, $group);
        } else {
            $result['page'] = max(1, $page);
            $result['rows'] = $limit;
            $result['total'] = $this->db->count($sql, $cond, '1');
            $result['data'] = $this->db->find($sql, $cond, $order, $page, $limit, '', $select, $group);
        }
        empty( $result['data']) &&  $result['data']=[];
        return $result;
    }

	/**
     * @param array  $table ['user b'=>['JOIN'=>'left','ON'=>'a.uid=b.uid']]
     * @param array  $order
     * @param int    $page
     * @param int    $limit
     * @param string $select

     * @return array|bool
     */
	public function selectWith(array $join = [],array $cond = [],array $order = [],int  $page = 0,int $limit = 0,string $select = '*',string $key = '',string $group = '')
    {
        $str = [];
        foreach ($join as $k=> $v) {
            $str[] = (empty($v['JOIN']) ? 'LEFT' : $v['JOIN']) . ' JOIN ' . $k . ' ON ' . $v['ON'];
        }
        return $this->db->find($this->table . ' a1 ' . implode(' ', $str), $cond, $order, $page, $limit, $key, $select, $group);
    }


    /**
     * 查询一个列表分页
     */
    public function GetList(array $cond, array $order = [], int $page = 1, int $limit = 1000, string $select = '*', bool $by_page = true, string $group = ''):array
    {
          !isset($cond['IsDelete']) && $cond['IsDelete'] = 0;
        $result=[];
        $reverse_page=$page;
        $total_page=0;
        if ($by_page && $limit) {
            $result['total'] = $this->count($cond, "1");
            $total_page = ceil($result['total'] / $limit);
            $reverse_page = max(100,ceil($total_page / 2));
        }
        $index = StoreProductConst::pk;
        $list=[];
        if (!empty($index)) {
            if($page > $reverse_page) {
                $zpage = max(1, $total_page - $page + 1) ;
                foreach ($order as $k => $row){
                    $order[$k] = $row==1 ? -1:1;
                }
                $index_list = $this->select($cond, $order,  $zpage, $limit, $index,'', $group);
                $index_list = array_reverse($index_list, TRUE);
            }else{
                $index_list = $this->select($cond, $order,  $page, $limit, $index,'', $group);
            }

            if(!empty($index_list)){
                    $index_array  = arrlist_values($index_list,$index);
                    $list =  $this->select([$index=>$index_array], [], 0,0, $select);
            }
            unset($index_list, $index_array);
        } else {
            if($page > $reverse_page) {
                $zpage = max(1, $total_page - $page + 1) ;
                foreach ($order as $k => $row){
                    $order[$k] = $row==1 ? -1:1;
                }
                $list = $this->select($cond, $order, $zpage, $limit, $select,'', $group);
                $list = array_reverse($list, TRUE);
            }else{
                $list = $this->select($cond, $order,  $page, $limit, $select,'', $group);
            }
        }

        if (!$by_page) {
            $result['data'] = $list;
        } else {
            $result['page'] = min(max(1, $page), 200000000);
            $result['rows'] = $limit;
            $result['data'] = $list;
        }
        empty( $result['data']) &&  $result['data']=[];
        return $result;
    }

    /**
     * 查询数据
     */
    public function select(array $cond = [],array  $order = [],int $page = 0,int $limit = 0,string $select = '*',string $key = '',string $group = ''):array
    {
        if (is_string($select) && $select != '*') {
            $select = explode(',', $select);
        }
                  !isset($cond['IsDelete']) && $cond['IsDelete'] = 0;
        return $this->db->find($this->table, $cond, $order, $page, $limit, $key, $select, $group);
    }

    /**
     * 查询一条数据
     */
    public function find_one($cond, $order = [], $select = '*'):array|bool
    {
                  !isset($cond['IsDelete']) && $cond['IsDelete'] = 0;
        return $this->db->find_one($this->table, $cond, $order, $select);
    }

    // hook model_store_product_end.php
}

?>